
import {
    output,
    print
} from 'nc-lightapp-front';

import Common from '../../../../../public/actions/employing/common';
import {getAppPageConfig, saveValidate} from "../../../../../../hrpub/common/utils/utils";

export default class Main extends Common {
    constructor(comp) {
        super();
        this.comp = comp;
    }

    didAllInstance = () => {
        this.setButtonHandleMap();
    }

    // 设置按钮事件map
    setButtonHandleMap = () => {
        const {action} = this.comp;

        this.buttonHandleMap = {
            'save': this.saveAddPage,
            'browse_status': {
                'edit': this.toAddPageEditStatus,
                'submit': this.submitFromCard,
                'callback': this.callbackFromCard,
                'delete': this.deleteBill,
                'copy': action.rowAct.copyOnes,
                'excute': this.excuteFromCard,
                'print': this.printIt,
                'output': this.output,
                'CheckBudget':  action.orgSta.openOrgSituationModal,
                'cardrpt': this.jointSearch,
                'send_offer': this.operateOfferMethod('openOfferModal'),
                'accept_offer': this.operateOfferMethod('acceptOffer'),
                'reject_offer': this.operateOfferMethod('rejectOffer'),
                'submit_offer': this.operateOfferMethod('submitOffer'),
                'add': action.formAct.toAddPage,
                'refresh': action.formAct.toBrowsePage,
                'file': this.comp.props.fileManager
            }
        };
    }

    // 操作offer
    operateOfferMethod = (methodName) => {
        return async (selectedRows) => {
            const {action} = this.comp;
            await action.offerAct[methodName](selectedRows);
            await action.formAct.toBrowsePage(selectedRows);
        }
    }

    // 从卡片页面提交
    submitFromCard = async (selectedRows) => {
        const {action} = this.comp;

        await action.rowAct.submitOnes(selectedRows);

        action.formAct.toBrowsePage(selectedRows);
    }

    // 从卡片页面收回
    callbackFromCard = async (selectedRows) => {
        const {action} = this.comp;

        await action.rowAct.callbackOnes(selectedRows);
        action.formAct.toBrowsePage(selectedRows);
    }

     // 从卡片页面执行
     excuteFromCard = async (selectedRows) => {
        const {action} = this.comp;

        await action.rowAct.excuteOnes(selectedRows);

        action.formAct.toBrowsePage(selectedRows);
    }
    // 删除一个申请单据
    deleteBill = (selectedRows) => {
        this.comp.action.rowAct.deleteRows(selectedRows)
            .then((res) => {
                if(res) {
                    this.goToBackMainPage();
                }
            });
    }

    // 新增页面头部按钮点击处理
    addHeaderClick = (btnCode) => {
        const {props} = this.comp;
        const {form} = props;
        return (props, bCode) => {

            let selectedRows = [{
                ...form.getAllFormValue('card').rows[0]
            }];
            let handle = this.buttonHandleMap[btnCode];
            
            if(typeof handle === 'function') {
                handle(selectedRows);
            }
            else {
                typeof handle[bCode] === 'function' && handle[bCode](selectedRows);
            }
        }
    }

    // 从浏览态变成编辑态
    toAddPageEditStatus = (selectedRows) => {
        this.comp.action.rowAct.editOnes(selectedRows);
    }

    // 新增页面保存
    saveAddPage = () => {
        const {props, action} = this.comp;
        const {dispatch, form, emp} = props;

        if(form.isCheckNow('card')) {
            let postData = {
                model: form.getAllFormValue('card'),
                pk_org: emp.orgValue.refpk
            };
            let meta = props.meta.getMeta();
            let bodys_code = meta.formrelation['card'] || [];
            saveValidate(props, 'card', 'card', bodys_code, 'extcard', 'form')
                .then(() => {
                    dispatch({
                        type: 'emp/addPageSave',
                        payload: {
                            postData: postData
                        }
                    })
                        .then((res) => {
                            if (res.success) {
                                this.toast({
                                    color: 'success',
                                    content: emp.language['gx6008-000030'] // 保存成功
                                });
                                action.formAct.toBrowseStatus(res.data.head.card);
                            }
                        });
                })
        }
    }

    // 返回按钮返回主页面表格
    goToBackMainPage = () => {
        const {props,action} = this.comp;
        const {dispatch, button,emp} = props;

        this.update({
            page: 'main'
        });
       if(emp.widget){
        button.setButtonVisible({
            add: false,
            edit: false,
            delete: false,
            query: false,
            submit: false,
            excute: true,
            print: false,
            batchadd: false,
            callback: false,
            approveinfo: false,
            refresh: true,
            save: false,
            cancel: false,
            first: false,
            pre: false,
            next: false,
            last: false,
            copy: false,
            assfunc: true,
            cardrpt: false,
            send_offer: false,
            accept_offer: false,
            reject_offer: false,
            submit_offer: false,
            file: false
        });
        this.pubSub.publish('getWidgetTableData');
       }else{
        button.setButtonVisible({
            add: true,
            edit: false,
            delete: true,
            query: true,
            submit: true,
            print: true,
            batchadd: true,
            callback: true,
            approveinfo: true,
            refresh: true,
            save: false,
            cancel: false,
            first: false,
            pre: false,
            next: false,
            last: false,
            copy: false,
            assfunc: true,
            cardrpt: false,
            send_offer: false,
            accept_offer: false,
            reject_offer: false,
            submit_offer: false,
            file: false
        });
        button.setButtonVisible({
            save: false,
            cancel: false
        });
        this.pubSub.publish('getMainTableData');
       }
    }

    // 表单编辑前
    formBeforeEdit = async (platFormProps, formId, key, value, data) => {
        const {props} = this.comp;
        const {emp, dispatch, form, meta} = props;
        
        try {
            let res = await dispatch({
                type: 'emp/formEditBefore',
                payload: {
                    postData: {
                        key: key,
                        pk_org: emp.orgValue.refpk
                    }
                    
                }
            });
            let template = meta.getMeta();
            // 自定义参照的时候不返回refParam， 原先的写法 不会添加pk_org 导致没有数据
            ['card', 'psninf', 'tailinfo', 'auditinfo'].forEach((item) => {
                template[item].items.forEach((item) => {
                    if(item.attrcode === key && item.itemtype === 'refer') {
                        if(!item.queryCondition) item.queryCondition = {}
                        item.queryCondition['pk_org'] = emp.orgValue.refpk
                       if(res.data && res.data.refParam) Object.assign(item.queryCondition, res.data.refParam);
                    }
                });
            });
            
            await new Promise((resolve, reject) => {
                meta.setMeta(template, resolve);
            });
        }
        catch(e) {
        }
        return true;
    }

    // 表单编辑后
    formAfterEdit = (platFormProps, formId, key, value, preVal) => {
        const {props} = this.comp;
        const {emp, dispatch, form, meta} = props;

        let formData = form.getAllFormValue('card');

        let postData = {
            key: key,
            model: formData,
            pk_org: emp.orgValue.refpk
        };

        dispatch({
            type: 'emp/formEditAfter',
            payload: {
                postData: postData
            }
        })
            .then((res) => {
                if(res.data && res.data.head && res.data.head.card) {
                    form.setAllFormValue(res.data.head);
                }
            });
    }

    // 取消编辑
    cancelFormEdit = () => {
        const {props, action} = this.comp;
        const {emp, dispatch, form, meta, button} = props;

        this.promptBox({
            color: 'info',
            title: emp.language['gx6008-000036'], // '确认取消',
            content: emp.language['gx6008-000037'], // '是否确认取消
            beSureBtnClick: () => {
                let formValue = form.getAllFormValue('card');
                let billId = formValue.rows[0].values['pk_entryapply'].value;

                if(emp.page === 'add') {
                    this.cancelPost();
                }
                if(emp.page === 'add' || !billId) {
                    this.goToBackMainPage();
                }
                else {
                    this.showHistoryData();
                    action.formAct.toBrowseStatus();
                }
                
            }
        });
    }

    // 根据存储的数据展示编辑前
    showHistoryData = () => {
        const {props} = this.comp;
        const {emp, dispatch, form} = props;

        if(emp.addPageHistoryData) {
            form.setAllFormValue({
                card: emp.addPageHistoryData
            });
            this.update({
                addPageHistoryData: null 
            });
        }
    }

    // 新增取消需要请求一个接口
    cancelPost = () => {
        const {props, action} = this.comp;
        const {emp, dispatch, form, meta, button} = props;

        let postData = {
            model: form.getAllFormValue('card'),
            pk_org: emp.orgValue.refpk
        };

        return dispatch({
            type: 'emp/cancelAdd',
            payload: {
                postData: postData
            }
        });
    }

    // 打印
    printIt = () => {
        let formValue = this.comp.props.form.getAllFormValue('card');
        const appConfig = getAppPageConfig();
        print('pdf', '/nccloud/hrtrn/entrymng/EntryPrintAction.do', {
            appcode: appConfig.appcode,
            nodekey: '60081010',
            oids: [formValue.rows[0].values['pk_entryapply'].value]
        });
    }

    // 输出
    output = () => {
        const {props} = this.comp;
        const {
            emp
        } = props;
        let formValue = this.comp.props.form.getAllFormValue('card');
        const appConfig = getAppPageConfig();
        output({
            url: '/nccloud/hrtrn/entrymng/EntryPrintAction.do',
            data: {
                appcode: appConfig.appcode,
                nodekey: '60081010',
                oids: [formValue.rows[0].values['pk_entryapply'].value],
                outputType: 'output',
                filename: emp.language['gx6008-000067'] // 录用办理
            },
            callback: () => {
            }
        });
    }

    // 联查人员卡片
    jointSearch = async () => {
        const {props} = this.comp;
        const {form, btnAct} = props;
        
        let formData = form.getAllFormValue('card');
        
        // btnAct.cardViewRef.openCardViewModal(formData.rows);
        btnAct.wpsview.openView(formData.rows)
    }
}